package com.linjian.togetherbirthday.fragment;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.linjian.togetherbirthday.MainActivity;
import com.linjian.togetherbirthday.R;
import com.linjian.togetherbirthday.base.BaseFragment;
import com.linjian.togetherbirthday.bean.DateOrPartyBean;
import com.linjian.togetherbirthday.contant.HttpContant;
import com.linjian.togetherbirthday.utils.HttpUtils;
import com.linjian.togetherbirthday.utils.NoticeEvent;
import com.linjian.togetherbirthday.utils.SharedPreferencesUtil;
import com.linjian.togetherbirthday.view.CustomDatePickerTwo;
import com.sdsmdg.tastytoast.TastyToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ReleaseDateFragment extends BaseFragment implements View.OnClickListener {

    private ImageView backIv;
    private TextView titleTv, rightTv;
    private TextView nanTv,nvTv,allSexTv,addressTv,timeTv,myPayTv,AAPayTv,youPayTv;
    private EditText expectEt,instructionsEt;

    private int sexType;
    private int whyPayType;

    private MainActivity activity;

    public static ReleaseDateFragment newInstance(String info) {
        ReleaseDateFragment releaseDateFragment = new ReleaseDateFragment();
        Bundle bundle = new Bundle();
        bundle.putString("info",info);
        releaseDateFragment.setArguments(bundle);
        return releaseDateFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int setView() {
        return R.layout.fragment_release_date;
    }

    @Override
    protected void init(View view) {
        activity = (MainActivity)getActivity();
        backIv = view.findViewById(R.id.layout_head_back_iv);
        titleTv = view.findViewById(R.id.layout_head_title_tv);
        rightTv = view.findViewById(R.id.layout_head_right_tv);

        nanTv = view.findViewById(R.id.release_date_nan);
        nvTv = view.findViewById(R.id.release_date_nv);
        allSexTv = view.findViewById(R.id.release_date_all);
        addressTv = view.findViewById(R.id.choose_date_address);
        timeTv = view.findViewById(R.id.choose_date_time);
        myPayTv = view.findViewById(R.id.my_pay_tv);
        AAPayTv = view.findViewById(R.id.AA_pay_tv);
        youPayTv = view.findViewById(R.id.you_pay_tv);
        expectEt = view.findViewById(R.id.expect_et);
        instructionsEt = view.findViewById(R.id.instructions_et);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        dateOrParty();
        titleTv.setText("约会");
        rightTv.setText("发布");

        if (getArguments()!=null){
            if (getArguments().getString("info")!=null){
                if (getArguments().getString("info").length() > 5){
                    String info = getArguments().getString("info").split(":")[0];
                    String info2 = getArguments().getString("info").split(":")[1];
                    addressTv.setText(info2);
                }

            }
        }
        setListener();
    }

    private void setListener() {
        backIv.setOnClickListener(this);
        rightTv.setOnClickListener(this);
        nanTv.setOnClickListener(this);
        nvTv.setOnClickListener(this);
        allSexTv.setOnClickListener(this);
        addressTv.setOnClickListener(this);
        timeTv.setOnClickListener(this);
        myPayTv.setOnClickListener(this);
        AAPayTv.setOnClickListener(this);
        youPayTv.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_head_back_iv:
                getActivity().getSupportFragmentManager().popBackStack();
                break;
            case R.id.layout_head_right_tv:
                if (sexType == 0||TextUtils.isEmpty(expectEt.getText())||TextUtils.isEmpty(instructionsEt.getText())||addressTv.getText().toString().equals("选择要约会的地点")||timeTv.getText().toString().equals("选择要约会的时间")||whyPayType == 0){
                    TastyToast.makeText(getActivity(),"选项不能为空",TastyToast.LENGTH_SHORT,TastyToast.WARNING).show();
                }else {
                    String whyPay = "";
                    String sex = "";
                    switch (whyPayType){
                        case 1:
                            whyPay = "我买单";
                            break;
                        case 2:
                            whyPay = "AA";
                            break;
                        case 3:
                            whyPay = "你请客";
                            break;
                    }
                    switch (sexType){
                        case 1:
                            sex = "男生";
                            break;
                        case 2:
                            sex = "女生";
                            break;
                        case 3:
                            sex = "男女不限";
                            break;
                    }
                    releaseOnADate(1
                            , "约会"
                            , 1
                            , sex
                            , expectEt.getText().toString()
                            , instructionsEt.getText().toString()
                            , dateOrPartyBean.getData().get(0).getParentid()
                            ,addressTv.getText().toString()
                            , "深圳"
                            , timeTv.getText().toString()
                            , "1"
                            ,whyPay
                            ,"0");
                }

                break;
            case R.id.release_date_nan:
                sexType = 1;
                nanTv.setTextColor(getResources().getColor(R.color.colorTextMain));
                nvTv.setTextColor(getResources().getColor(R.color.colorGrayFour));
                allSexTv.setTextColor(getResources().getColor(R.color.colorGrayFour));
                break;
            case R.id.release_date_nv:
                sexType = 2;
                nanTv.setTextColor(getResources().getColor(R.color.colorGrayFour));
                nvTv.setTextColor(getResources().getColor(R.color.colorTextMain));
                allSexTv.setTextColor(getResources().getColor(R.color.colorGrayFour));
                break;
            case R.id.release_date_all:
                sexType = 3;
                nanTv.setTextColor(getResources().getColor(R.color.colorGrayFour));
                nvTv.setTextColor(getResources().getColor(R.color.colorGrayFour));
                allSexTv.setTextColor(getResources().getColor(R.color.colorTextMain));
                break;
            case R.id.choose_date_address:
                activity.replaceFragment("FoodFragment","");
                break;
            case R.id.choose_date_time:
                CustomDatePickerTwo customDatePickerTwo = new CustomDatePickerTwo(getActivity()
                        , new CustomDatePickerTwo.ResultHandler() {
                    @Override
                    public void handle(String time) {
                        timeTv.setText(time);
                    }
                }
                ,"2018-12-12 12:30"
                ,"2019-12-12 12:30");
                customDatePickerTwo.show("2018-12-12 12:30");
                customDatePickerTwo.setIsLoop(false);
                break;
            case R.id.my_pay_tv:
                whyPayType = 1;
                myPayTv.setTextColor(getResources().getColor(R.color.colorTextMain));
                AAPayTv.setTextColor(getResources().getColor(R.color.colorGrayFour));
                youPayTv.setTextColor(getResources().getColor(R.color.colorGrayFour));
                break;
            case R.id.AA_pay_tv:
                whyPayType = 2;
                myPayTv.setTextColor(getResources().getColor(R.color.colorGrayFour));
                AAPayTv.setTextColor(getResources().getColor(R.color.colorTextMain));
                youPayTv.setTextColor(getResources().getColor(R.color.colorGrayFour));
                break;
            case R.id.you_pay_tv:
                whyPayType = 3;
                myPayTv.setTextColor(getResources().getColor(R.color.colorGrayFour));
                AAPayTv.setTextColor(getResources().getColor(R.color.colorGrayFour));
                youPayTv.setTextColor(getResources().getColor(R.color.colorTextMain));
                break;
        }
    }

    DateOrPartyBean dateOrPartyBean;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMsg(NoticeEvent event) {
        switch (event.getCls()) {
            case "requestFail":
                TastyToast.makeText(getActivity(), "请求失败", TastyToast.LENGTH_SHORT, TastyToast.ERROR).show();
                break;
            case "releaseOnADate":
                try {
                    JSONObject object = new JSONObject(event.getData().toString());
                    if (object.getInt("code") == 200) {
                        TastyToast.makeText(getActivity(), object.getString("data"), TastyToast.LENGTH_SHORT, TastyToast.SUCCESS).show();
                        getActivity().getSupportFragmentManager().popBackStack();
                    } else {
                        TastyToast.makeText(getActivity(), object.getString("msg"), TastyToast.LENGTH_SHORT, TastyToast.ERROR).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case "DateOrParty":
                Log.i("DateOrParty", event.getData().toString());
                try {
                    JSONObject object = new JSONObject(event.getData().toString());
                    if (object.getInt("code") == 200) {
                        dateOrPartyBean = new Gson().fromJson(event.getData().toString(), DateOrPartyBean.class);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 发布活动
     * "eventtype":1,
     * "etname":"约会",
     * "eventobject":1,
     * "eoname":"男生",
     * "eventexpect":"期望期望",
     * "eventexplain":"说明说明",
     * "placeid":1,
     * "placename":"海里捞火锅",
     * "placecity":"深圳",
     * "eventdate":"2018-11-18 19:00:00",
     * "costtype":"1",
     * "ctname":"AA",
     * "hidemember":"0"
     */
    private void releaseOnADate(int eventtype, String etname, int eventobject, String eoname, String eventexpect, String eventexplain, int placeid, String placename, String placecity, String eventdate, String costtype, String ctname, String hidemember) {
        Map<String, Object> map = new HashMap<>();
        map.put("eventtype", eventtype);
        map.put("etname", etname);
        map.put("eventobject", eventobject);
        map.put("eoname", eoname);
        map.put("eventexpect", eventexpect);
        map.put("eventexplain", eventexplain);
        map.put("placeid", placeid);
        map.put("placename", placename);
        map.put("placecity", placecity);
        map.put("eventdate", eventdate);
        map.put("costtype", costtype);
        map.put("ctname", ctname);
        map.put("hidemember", hidemember);
        HttpUtils.PutCookie(HttpContant.URL + HttpContant.ReleaseActivity
                , "SESSION=" + String.valueOf(SharedPreferencesUtil.get(getActivity(), "Cookie", ""))

                , map
                , new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        EventBus.getDefault().post(new NoticeEvent("requestFail"));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        EventBus.getDefault().post(new NoticeEvent("releaseOnADate", response.body().string()));
                    }
                });
    }

    /**
     * 进入页面请求获取约会或聚会数据
     */
    private void dateOrParty() {
        HttpUtils.doGet(HttpContant.URL + HttpContant.DateOrParty
                , "SESSION=" + String.valueOf(SharedPreferencesUtil.get(getActivity(), "Cookie", ""))
                , new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        EventBus.getDefault().post(new NoticeEvent("requestFail"));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        EventBus.getDefault().post(new NoticeEvent("DateOrParty", response.body().string()));
                    }
                });
    }
}
